import 'dart:math';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:meta/meta.dart';
import 'package:numberpicker/numberpicker.dart';
import 'package:list_test/weight.dart';

class AddEntryDialog extends StatefulWidget {
  final Weight initWeightModel;
  final double defaultWeight;

  AddEntryDialog.edit(this.initWeightModel): defaultWeight = null;
  AddEntryDialog.add(this.defaultWeight)
    : initWeightModel = new Weight(new DateTime.now(), defaultWeight, null);

  @override
  AddEntryDialogState createState () {
    return new AddEntryDialogState(initWeightModel.dateTime, initWeightModel.weight, initWeightModel.note);
  }
}

class DateTimeItem extends StatelessWidget {
  DateTimeItem({Key key, DateTime dateTime, @required this.onChange})
    : assert(onChange != null),
      date = dateTime == null
        ? new DateTime.now()
        : new DateTime(dateTime.year, dateTime.month, dateTime.day),
      time = dateTime == null
        ? new DateTime.now()
        : new TimeOfDay(hour: dateTime.hour, minute: dateTime.minute),
        super(key: key);

  final DateTime date;
  final TimeOfDay time;
  final ValueChanged<DateTime> onChange;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Row(
      children: <Widget>[
        new Expanded(
          child: new InkWell(
            onTap: (() => _showDatePicker(context)),
            child: new Padding(
              padding: EdgeInsets.symmetric(vertical: 8.0),
              child: new Text(new DateFormat('EEEE, MMMM d').format(date)),
            ),
          ),
        ),
        new InkWell(
          onTap: (() => _showTimePicker(context)),
          child: new Padding(
            padding: EdgeInsets.symmetric(vertical: 8.0),
            child: new Text(time.format(context).toLowerCase()),
          ),
        )
      ],
    );
  }

  _showDatePicker (BuildContext context) async {
    DateTime datePicked = await showDatePicker(
      context: context,
      initialDate: date,
      firstDate: date.subtract(const Duration(days: 2000)),
      lastDate: new DateTime.now()
    );

    if (datePicked != null) {
      onChange(new DateTime(
        datePicked.year,
        datePicked.month,
        datePicked.day,
        time.hour,
        time.minute
      ));
    }
  }

  _showTimePicker (BuildContext context) async {
    TimeOfDay timePicked = await showTimePicker(
      context: context,
      initialTime: time,
    );

    if (timePicked != null) {
      onChange(new DateTime(
        date.year,
        date.month,
        date.day,
        timePicked.hour,
        timePicked.minute
      ));
    }
  }
}

class AddEntryDialogState extends State<AddEntryDialog> {
  DateTime _dateTime = new DateTime.now();
  double _weight;
  String _note;
  TextEditingController _textController;

  AddEntryDialogState(this._dateTime, this._weight, this._note);
  Widget _createAppBar (BuildContext context) {
    return new AppBar(
      title: const Text('New Entry'),
      actions: <Widget>[
        new FlatButton(
          onPressed: () {
            Navigator
              .of(context)
              .pop(new Weight(_dateTime, _weight, _note));

          },
          child: new Text('Save', 
            style: Theme.of(context).textTheme.subhead.copyWith(color: Colors.white),
          ),
        )
      ],
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _textController = new TextEditingController(text: _note);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: _createAppBar(context),
      body: new Column(
        children: <Widget>[
          new ListTile(
            leading: new Icon(Icons.today, color: Colors.grey[500]),
            title: new DateTimeItem(
              dateTime: _dateTime,
              onChange: (dateTime) => setState(() => _dateTime = dateTime),
            ),
          ),
          new ListTile(
            leading: new Image.asset(
              'assets/scale-bathroom.png',
              color: Colors.grey[500],
              height: 24.0,
              width: 24.0,
            ),
            title: new Text('$_weight kg'),
            onTap: () => _showWeightPicker(context),
          ),
          new ListTile(
            leading: new Icon(Icons.speaker_notes, color: Colors.grey[500]),
            title: new TextField(
              decoration: new InputDecoration(
                hintText: 'Optional note'
              ),
              controller: _textController,
              onChanged: (value) => _note = value,
            )
          ),
        ],
      ),
    );
  }

  _showWeightPicker (BuildContext context) async {
    double weight = await showDialog(
      context: context,
      builder: (BuildContext context) {
        return new NumberPickerDialog.decimal(
          minValue: 1,
          maxValue: 150,
          initialDoubleValue: _weight,
          title: new Text('Enter your weight'),
        );
      }
    );

    if (weight != null) {
      setState(() => _weight = weight);
    }
  }
}